package com.jzo2o.customer.controller.consumer;

import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.enums.AddressDefaultStatusEnum;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author JIAN
 */
@RestController("consumerAddressBookController")
@RequestMapping("/consumer/address-book")
@Api(tags = "用户端 - 地址簿相关接口")
public class AddressBookController {
    @Resource
    private IAddressBookService addressBookService;

    /**
     * 增加地址信息
     */
    @PostMapping
    public void add(@RequestBody AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        addressBookService.insert(addressBookUpsertReqDTO);
    }

    /**
     * 查询地址信息
     */
    @GetMapping("/page")
    public PageResult<AddressBook> page(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        return addressBookService.page(addressBookPageQueryReqDTO);
    }

    /**
     * 查询指定id的地址信息(展示详情)
     */
    @GetMapping("/{id}")
    public AddressBook getById(@PathVariable Long id) {
        return addressBookService.getById(id);
    }

    /**
     * 更改指定id的地址信息(修改地址)
     */
    @PutMapping("/{id}")
    public void updateById(@PathVariable Long id,
                           @RequestBody AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        addressBookService.updateById(id, addressBookUpsertReqDTO);
    }

    /**
     * 删除指定id的地址信息(逻辑删除)
     */
    @DeleteMapping("/batch")
    public void deleteBatch(@RequestBody List<Long> ids) {
        addressBookService.removeByIds(ids);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/default")
    public void updateDefault(@RequestParam Long id, @RequestParam int flag) {
        if (flag != AddressDefaultStatusEnum.DEFAULT.getStatus()
                && flag != AddressDefaultStatusEnum.NONE_DEFAULT.getStatus()) {
            throw new ForbiddenOperationException("设置的参数有误拒绝请求");
        }

        addressBookService.updateDefault(id, flag);
    }

    @GetMapping("/defaultAddress")
    public AddressBook getDefaultAddress() {
        return addressBookService.getDefaultAddress();
    }
}